package com.yups.dao;
import com.yups.model.Coach;
import com.yups.model.Technicain;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * 教练数据操作类
 *
 * @author 于鹏生
 */
public class TechnicainDao extends BaseDao implements ResultSetHandler<List<Coach>> {

	public Coach getCoachById(int id) {
		try {
			String sql = "select id, company, photo, avatar, nickname,"
					+ " price, message, distance"
					+ " from coach where id = ?";
			return queryRunner.query(sql, rs -> {
				Coach coach = null;
				if (rs.next()) {
					coach = new Coach(
							rs.getInt("id"),
							rs.getString("company"),
							rs.getString("photo"),
							rs.getString("avatar"),
							rs.getString("nickname"),
							rs.getDouble("price"),
							rs.getString("message"),
							rs.getDouble("lat"),
							rs.getDouble("lon")
					);
				}
				return coach;
			}, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public List<Technicain> getAll() {
		try {
			String sql = "select id, company, logo, avatar, nickname,"
					+ " price, message, detail, lat, lon from coach"
					+ " order by id";
			return queryRunner.query(sql, new BeanListHandler<>(Technicain.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<Coach> handle(ResultSet rs) throws SQLException {
		List<Coach> coachs = new LinkedList<>();
		while (rs.next()) {
			coachs.add(new Coach(
					rs.getInt("id"),
					rs.getString("company"),
					rs.getString("photo"),
					rs.getString("avatar"),
					rs.getString("nickname"),
					rs.getDouble("price"),
					rs.getString("message"),
					rs.getDouble("lat"),
					rs.getDouble("lon")
			));
		}
		return coachs;
	}
}
